<template>
  <div>
    <div v-for="(item,index) in catsList" :key="index" class="cats-list">
      <div class="cats-list-item">
        <div>{{ item.gender }}</div>
        <p v-for="cat in item.catsList" :key="cat.name">{{ cat.name }}</p>
      </div>
    </div>
  </div>
</template>

<script>
export default {
  name: 'CatsList',
  data () {
    return {
      url: 'http://5c92dbfae7b1a00014078e61.mockapi.io/owners',
      catsList: []
    }
  },
  created () {
    this.reqOwnersList();
  },
  methods: {
    reqOwnersList () {
      this.axios(this.url).then(res => {
        let ownersList = res.data;
        let genders = new Set(ownersList.map(owner => owner.gender));
        genders = [...genders];

        if (genders.length) {
          genders.forEach((gender, i) => {
            let tempList = ownersList.filter(owner => owner.gender === gender);
            let petsList = [];
            let catsList = [];
            
            if (tempList.length) {
              tempList.forEach(owner => {
                if (owner.pets && owner.pets.length) {
                  petsList.push(owner.pets)
                }
              });
            }
            if (petsList.length) {
              catsList = petsList.flat().filter(pet => pet.type === 'Cat');
              catsList.sort((itemN, itemM) => itemN.name > itemM.name ? 1 : -1);
            }

            this.catsList[i] = {
              gender,
              catsList
            }
            this.$forceUpdate();
          })
        }
      })
    }
  },
}
</script>

<style lang="scss" scoped>
.cats-list {
  width: 500px;
  margin-left: 100px;
  font-size: 20px;
  font-weight: 550;
  .cats-list-item {
    margin: 25px 0px;
    p {
      padding-left: 80px;
    }
  }
}
</style>